//
//  CZ.swift
//  GZWeibo007
//
//  Created by Apple on 15/12/17.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit

import AFNetworking
/*

/// 转发数
var reposts_count: Int = 0

/// 评论数
var comments_count: Int = 0

/// 表态数(赞)
var attitudes_count: Int = 0


*/


// 使用枚举来统一管理错误
enum CZNetworkError: Int {
    
    case emptyAccessToken = -1  // AccessToken没有值
    
    case emptyUid = -2  // Uid没有值
    
    var errorDescription: String {
        get {
            
            switch self {
            case CZNetworkError.emptyAccessToken:
                return "access_token没有值"
            case CZNetworkError.emptyUid:
                return "uid没有值"
            }
        }
    }
    func error() -> NSError {
        return NSError(domain: "cn.itcast.error.network", code: self.rawValue, userInfo: ["errorDescription" : self.errorDescription])
    }
}

/// 网络工具类只负责请求数据,请求到数据后回调.不去处理数据
class CZNetworkTool: AFHTTPSessionManager {
    
    static let sharedInstance: CZNetworkTool = CZNetworkTool()
    
    // 不让别人访问构造方法
    private init () {
        // 没有初始化的属性
        let baseURL = NSURL(string: "https://api.weibo.com/")!

        super.init(baseURL: baseURL, sessionConfiguration: nil)
        self.responseSerializer.acceptableContentTypes?.insert("text/plain")
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 授权相关
    /*
    App Key：
    4211991686
    App Secret：
    4979c9136465c227fe45577d5d7197e4
    */
    /// app key
    private let client_id = "3199538560"
    
    /// app 秘钥
    private let client_secret = "5a4e2447eb33f9e3168e4c84861a9c07"
    
    /// 授权回调地址
    let redirect_uri = "https://api.weibo.com/oauth2/default.html"
    
    /// 拼接登陆界面的URL地址
    func oAuthURL() -> NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        
        return NSURL(string: urlString)!
    }
    
    // MARK: - 加载AccessToken
    // 当网络请求成功会失败需要告诉调用的对象,使用闭包回调
    func loadAccessToken(code: String, finished: (result: [String: AnyObject]?, error: NSError?) -> ()) {
        // 6.准备相关内容
        // 6.1 url地址, 可以省略前面的baseURL,AFN会自动帮我们加上
        let urlString = "oauth2/access_token"
        
        // 6.2 请求参数,字典
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        // 7.发送POST请求
        POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            let dict = result as? [String : AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
                // 8.执行准备好的闭包
                finished(result: nil, error: error)
        }
    }
    
    /// MAR: - 加载用户信息
    func loadUserInfo(finished: (result: [String: AnyObject]?, error: NSError?) -> ()) {

//        CZUserAccount.loadUserAccount()?.access_token = nil
        guard let access_token = CZUserAccount.loadUserAccount()?.access_token else {
      
            
            let error = CZNetworkError.emptyAccessToken.error()
            finished(result: nil, error: error)
            return
        }
        
        guard let uid = CZUserAccount.loadUserAccount()?.uid else {
  
            
            
            let error = CZNetworkError.emptyUid.error()
            
            // 告诉调用者,网络请求出错
            finished(result: nil, error: error)
            return
        }
        
        // 能到这里来说明uid是有值的.
        
        // 3.url地址, 可以省略baseURL,AFN会自动帮我们加上
        let urlString = "2/users/show.json"
        
        // 4.请求参数
        let parameters = [
            "access_token": access_token,
            "uid": uid
        ]
        
        // 5.发送请求获取用户数据
        GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            // 6.调用准备好的闭包
            let dict = result as? [String: AnyObject]
//            有转发数等
//            print("****************\(dict)****************");
            finished(result: dict, error: nil)
            
            
            }) { (_, error) -> Void in
                // 6.调用准备好的闭包
                finished(result: nil, error: error)
        }
    }
    
    
    

     // MARK: - 获得评论
    /**
    根据微博ID返回某条微博的评论列表
    :param: id       需要查询的微博ID
    :param: since_id 若指定此参数，则返回ID比since_id大的评论（即比since_id时间晚的评论），默认为0
    count: 评论一次最大更新数
    :param: max_id   若指定此参数，则返回ID小于或等于max_id的评论，默认为0
    :param: success  请求成功回调result->成功 ;  error->失败
    
      https://api.weibo.com/2/comments/show.json///<请求URl
    */
     func loadStatusComment(id:Int ,since_id: Int, count: Int, max_id: Int, loadSuccessed: (result:[String: AnyObject]? , error: NSError?) ->()) {
        ///失败
        guard let access_token = CZUserAccount.loadUserAccount()?.access_token else {
            
            let error = CZNetworkError.emptyAccessToken.error();
            
            loadSuccessed(result: nil, error: error);
            return
        }
        
        let urlString = "2/comments/show.json";
        
        var parameters: [String: AnyObject] = ["access_token": access_token];
        
        parameters["id"] = id ;
        
        if since_id > 0 {///最新评论
            parameters["since_id"] = since_id;
        } else if max_id > 0 {///往时评论
            parameters["max_id"] = max_id - 1;
        }
        parameters["count"] = count;
        
        // 5.4. 发送请求
        GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            // 5.5.闭包回调,获得到数据
            let dict = result as? [String: AnyObject]
          
            
            
            
            loadSuccessed(result: dict, error: nil)
            
        }) { (_, error) -> Void in
            // 5.5.闭包回调,出现了错误
//            print("error:\(error)")
            loadSuccessed(result: nil, error: error);
    }
 

         }
    
    
    // MARK: 对一条微博进行评论
    
    /**对一条微博进行评论
    
    :param: comment       用户输入的内容
    :param: id            需要评论的微博ID。
    :param: commentStatus 评论内容，必须做URLencode，内容不超过140个汉字。
    
    https://api.weibo.com/2/comments/create.json
    */
    
    func commentStatus (comment:NSString,id:Int,commentStatus: (result:[String: AnyObject]? , error: NSError?) ->()) {
        ///失败
        
        guard let access_token = CZUserAccount.loadUserAccount()?.access_token else {
            
            let error = CZNetworkError.emptyAccessToken.error();
            
            commentStatus(result: nil, error: error)
            return
        }
        
        //原来的代码
//        guard let access_token = CZUserAccount.loadUserAccount()?.access_token else {
//            
//            let error = CZNetworkError.emptyAccessToken.error();
//            
//          //  loadSuccessed(result: nil, error: nil);
//            commentStatus(result: nil, error: error)
//            return
//        }
        
        if comment.length == 0{
            print("commentStatus");
            return;
        }
        
        let urlString = "2/comments/create.json";
        
        var parameters: [String: AnyObject] = ["access_token": access_token];
        
        parameters["id"] = id ;
        //不用转码  直接赋值就好
        parameters["comment"] = comment
//        parameters["comment"] = String(comment.UTF8String)
        
        POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            // 5.5.闭包回调,获得到数据
            let dict = result as? [String: AnyObject]
            
            commentStatus(result: dict, error: nil)
            
            
            }) { (_, error) -> Void in
                commentStatus(result: nil, error: error);
                print("评论出错\(error)");
        }
        
    }

    
    
    // MARK: - 转发一条微博
    
    /**
    转发一条微博
    
    :param: id               要转发的微博ID
    :param: status     添加的转发文本，必须做URLencode，内容不超过140个汉字，不填则默认为“转发微博”。
    :param: relaySuccessed 成败回调
    
    https://api.weibo.com/2/statuses/repost.json
    */
    func relayStatus(id:Int, status:NSString ,relaySuccessed: (result:[String: AnyObject]? , error: NSError?) ->()) {
        
        if status.length == 0{
            print("relayStatus");
            //跳转至转发
            return;
        }
        
        
        guard let access_token = CZUserAccount.loadUserAccount()?.access_token else {
            
            let error = CZNetworkError.emptyAccessToken.error();
            
            relaySuccessed(result: nil, error: error);
            return
        }
        
//        guard let access_token = CZUserAccount.loadUserAccount()?.access_token else {
//            
//            let error = CZNetworkError.emptyAccessToken.error();
//            
////            loadSuccessed(result: nil, error: error);
//            
//            return
//        }
        

        let urlString = "2/statuses/repost.json";
        
        var parameters: [String: AnyObject] = ["access_token": access_token];
        
        parameters["id"] = id ;
        
        //不用转码  直接赋值就好
        parameters["status"] = status
        
//        parameters["status"] = String(status.UTF8String)
        
        POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            let dict = result as? [String: AnyObject];
            relaySuccessed(result: dict, error: nil);
            }) { (_, error) -> Void in
                relaySuccessed(result: nil, error: error);
        }
        
        
    }
    
    
    // MARK: - 发布新微博
    /**发布新文字微博
    
    
    :param: status        微博内容（文字）
    :param: sendSuccessed 成败回调
    */
    func sendStatusOnlyTitle (status:NSString,sendSuccessed: (result:[String: AnyObject]? , error: NSError?) ->()) {
        
        if status.length == 0{
            print("提示：长度不能为0");
            return;
        }
        
        
        guard let access_token = CZUserAccount.loadUserAccount()?.access_token else {
            
            let error = CZNetworkError.emptyAccessToken.error();
            
            sendSuccessed(result: nil, error: error);
            return
        }
        
//        guard let access_token = CZUserAccount.loadUserAccount()?.access_token else {
//            
//            let error = CZNetworkError.emptyAccessToken.error();
//            
//            //            loadSuccessed(result: nil, error: error);
//            
//            return
//        }
        let urlString = "2/statuses/update.json";
        
        var parameters: [String: AnyObject] = ["access_token": access_token];
        
        //不用转码  直接赋值就好
        parameters["status"] = status
        
//      parameters["status"] = String(status.UTF8String);
        
        
        POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            let dict = result as? [String: AnyObject];
            sendSuccessed(result: dict, error: nil);
            }) { (_, error) -> Void in
              sendSuccessed(result: nil, error: error);
        }
    }
    

    
    
    
    
    
    
    
    // MARK: - 加载本地数据
    func loadLocalStatus(finished: (result: [String: AnyObject]?, error: NSError?) -> ()) {
        // 1.获取statuses.json的路径
        let path = NSBundle.mainBundle().pathForResource("statuses", ofType: "json")!
        
        // 2.加载到内存中(NSData)
        let data = NSData(contentsOfFile: path)!
        
        
        let json = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
        let dict = json as? [String: AnyObject]
        finished(result: dict, error: nil)
    }

    // MARK: - 获取微博数据
    /**
    加载微博数据(
    
    - parameter finished: 加载完数据的回调
    */
    func loadStatus(since_id: Int, max_id: Int, finished: (result: [String: AnyObject]?, error: NSError?) -> ()) {
        // 5.1. 判断access_token
        guard let access_token = CZUserAccount.loadUserAccount()?.access_token else {
            // access_token没有值
            // 5.1.2创建错误返回调用者
            let error = CZNetworkError.emptyAccessToken.error()
            finished(result: nil, error: error)
            return
        }
        
        // 5.2. url地址
        let urlString = "2/statuses/home_timeline.json"
        
        // 5.3. 请求参数
        var parameters: [String: AnyObject] = ["access_token": access_token]
        
        if since_id > 0 {
            // 表示别人传了since_id, 下拉刷新微博数据
            parameters["since_id"] = since_id
        } else if max_id > 0 {
            // 表示别人传了max_id, 上拉加载更多微博数据
            // 若指定此参数，则返回ID小于或等于max_id的微博,不需要等于的微博
            parameters["max_id"] = max_id - 1
        }
        
        let debug = false
        if debug {
            //            // debug模式,加载本地数据
            //            loadLocalStatus(finished)
        } else {
            // 5.4. 发送请求
            GET(urlString, parameters: parameters, success: { (_, result) -> Void in
                // 5.5.闭包回调,获得到数据
                let dict = result as? [String: AnyObject]
                
                finished(result: dict, error: nil)
                
                }) { (_, error) -> Void in
                    // 5.5.闭包回调,出现了错误
                    finished(result: nil, error: error)
            }
        }
        
    }
    
}
